package com.cardone.platform.common.support;

import com.cardone.common.service.SimpleService;
import com.cardone.context.ContextHolder;
import com.cardone.generator.script.GeneratorScript;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.support.TaskUtils;

import java.util.Map;
import java.util.Map.Entry;

/**
 * 初始化数据支持
 *
 * @author yaohaitao
 */
@Getter
@Setter
@Slf4j
public class InitDataSupport {
    @Setter
    private TaskExecutor taskExecutor;

    @Setter
    private boolean initData = true;

    @Setter
    private boolean initScript = true;

    public void init() {
        taskExecutor.execute(TaskUtils.decorateTaskWithErrorHandler(() -> {
            try {
                Thread.sleep(9000);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }

            if (initData) {
                Map<String, SimpleService> simpleServiceMap = ContextHolder.getApplicationContext().getBeansOfType(SimpleService.class);

                if (MapUtils.isNotEmpty(simpleServiceMap)) {
                    for (Entry<String, SimpleService> simpleServiceEntry : simpleServiceMap.entrySet()) {
                        try {
                            simpleServiceEntry.getValue().init();
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }

            if (initScript) {
                Map<String, GeneratorScript> generatorScriptMap = ContextHolder.getApplicationContext().getBeansOfType(GeneratorScript.class);

                if (MapUtils.isNotEmpty(generatorScriptMap)) {
                    for (Entry<String, GeneratorScript> generatorScriptEntry : generatorScriptMap.entrySet()) {
                        try {
                            generatorScriptEntry.getValue().run();
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
        }, null, true));
    }
}
